package com.huixh.train.common.controller;

//import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.huixh.train.common.exception.BusinessException;
import com.huixh.train.common.resp.Result;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author huixh
 */
@RestControllerAdvice
public class ControllerExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result<String> handleException(Exception e) throws Exception {
        logger.error("系统异常:{}", e);
        // if (RootContext.getXID() != null){
        //     throw e;
        // }
        e.printStackTrace();
        return Result.fail("系统未知异常，请联系管理员");
    }

    // @ExceptionHandler(value = FlowException.class)
    // public Result<String> handleFlowException(FlowException e) throws Exception {
    //     logger.error("熔断限流:{}", e.getMessage());
    //     return Result.fail("熔断限流，当前请求过载");
    // }

    @ExceptionHandler(value = BusinessException.class)
    public Result<String> handleServiceException(BusinessException e) {
        logger.error("业务异常:{}", e.getDesc());
        return Result.fail(e.getDesc());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public Result<String> handleBindException(ConstraintViolationException e) {
        StringBuilder errorMessageBuilder = new StringBuilder();
        e.getConstraintViolations().forEach(constraintViolation -> {
            errorMessageBuilder.append(constraintViolation.getMessage());
            errorMessageBuilder.append(",");
        });
        errorMessageBuilder.deleteCharAt(errorMessageBuilder.length() - 1);
        logger.error("请求参数校验异常:{}", errorMessageBuilder);
        return Result.fail(errorMessageBuilder.toString());
    }

    @ExceptionHandler(value = BindException.class)
    public Result<String> handleBindException(BindException e) {
        StringBuilder errorMessageBuilder = new StringBuilder();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            errorMessageBuilder.append(error.getDefaultMessage());
            errorMessageBuilder.append(",");
        }
        errorMessageBuilder.deleteCharAt(errorMessageBuilder.length() - 1);
        logger.error("请求对象校验异常:{}", errorMessageBuilder);
        return Result.fail(errorMessageBuilder.toString());
    }

}
